package cn.cloud9;

import java.util.*;

public class Case1GuessGame {

    /**
     * https://www.bilibili.com/video/BV18J411W7cE?p=52
     * 猜数字大小游戏
     * @param args
     */
    public static void main(String[] args) {
        Random random = new Random();
        boolean stillSettingRange = true; // 设置一个初始范围
        boolean shouldContinue = true; // 是否持续进行下去的变量
        final int MIN_RANGE = 10;
        final int MAX_RANGE = 100000000;
        int settingRange = MIN_RANGE; // 给予一个最小范围值
        int roundCount = 0; // 统计次数
        List<Map<String, Object>> record = new ArrayList<>();
        Map<String, Object> roundRecord = null;

        while (stillSettingRange) {
            Scanner scanner = new Scanner(System.in);
            System.out.println("请输入您希望预估的范围（10 ~ 100000000）：");
            if (!scanner.hasNextInt()) {
                System.out.println("输入错误，请输入有效的预估范围！");
                scanner.close();
                continue;
            }
            settingRange = scanner.nextInt();
            scanner.close();
            if (settingRange < MIN_RANGE) {
                System.out.println("输入范围小于10，请输入有效的预估范围！");
                continue;
            } else if (settingRange > MAX_RANGE) {
                System.out.println("输入范围大于100000000，请输入有效的预估范围！");
                continue;
            }
            System.out.println("设定成功！ 范围 1 ~ " + settingRange);
            stillSettingRange = false;
        }

        // random.nextInt(100) 随机数 0 ~ 99 , 加1 = 1 ~ 100
        final int RAND_NUM = random.nextInt(settingRange) + 1;

        while(shouldContinue) {
            // scanner资源和系统输入流资源无法重复使用，每一次必须新开一个
            Scanner scanner = new Scanner(System.in);
            System.out.println("请输入您预估的整数值（1 ~ " + settingRange + "）：");

            // 要先判断输入的是不是数字
            if (!scanner.hasNextInt()) {
                System.out.println("您输入的并不是一个整数，请重新输入！");
                scanner.close();
                continue;
            }

            int i = scanner.nextInt();
            scanner.close();

            ++ roundCount;
            roundRecord = new HashMap<>();
            roundRecord.put("roundCount", roundCount);
            roundRecord.put("value", i);
            record.add(roundRecord);

            if (i > RAND_NUM) {
                System.out.println("预估数值大于目标值！");
            } else if (i < RAND_NUM) {
                System.out.println("预估数值小于于目标值！");
            } else {
                shouldContinue = false; // 不再继续进行，游戏结束
                System.out.println("预估数值正确！ 本轮游戏一共" + roundCount + "次");
                record.forEach(map -> {
                    String currentRound = map.get("roundCount").toString();
                    String value = map.get("value").toString();
                    System.out.println("轮次" + currentRound + " 值：" + value + " 目标值：" + RAND_NUM);
                });
            }
        }
    }
}
